import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;

/**
 * Created by Kobe on 2016/12/5.
 */
public class Email {
    private static final String sendhost ="smtp.sina.com";
    private static final String receivehost ="pop.sina.com";
    private static final String home_address ="a623751908@sina.com";
    private static final String password="19961216";
    public static final int N = 3;


    //send the mail
    public static void sendMail(String target_address,String target_name){
        Properties props =System.getProperties();
        props.put("mail.smtp.host",sendhost);
        props.put("mail.smtp.auth","true");
        Session session =Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });
        try {
            MimeMessage message =new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(target_address));
            message.setSubject("java");
            message.setText("Dear "+target_name+",\n" +
                    "This is my Java homework,can you help me?Please answer the following question.\n" +
                    "Do you like me?");
            Transport.send(message);
        }  catch (MessagingException e) {
            e.printStackTrace();
        }
        session =null;
    }

    public static void sendMailWithFile(String target_address,String target_name,String filename){
        Properties props =System.getProperties();
        props.put("mail.smtp.host",sendhost);
        props.put("mail.smtp.auth","true");
        Session session =Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });
        try {
            MimeMessage message =new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(target_address));
            message.setSubject("mailWithFile");
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText("Dear "+target_name+",\n" +
                    "This is my Java homework,can you help me?Please answer the following question.\n" +
                    "Do you like me?");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            Transport.send(message);
        }  catch (MessagingException e) {
            e.printStackTrace();
        }
        session =null;
    }


    public static void sendMailWithImage(String target_address,String target_name,String filename){
        Properties props =System.getProperties();
        props.put("mail.smtp.host",sendhost);
        props.put("mail.smtp.auth","true");
        Session session =Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });
        try {
            MimeMessage message =new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(target_address));
            message.setSubject("mailWithFile");
            // Create your new message part
            BodyPart messageBodyPart = new MimeBodyPart();
            String htmlText = "<H1>Hello</H1>" +
                    "<img src=\"cid:memememe\">";
            messageBodyPart.setContent(htmlText, "text/html");
            MimeMultipart multipart = new MimeMultipart("related");
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart();
            DataSource fds = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(fds));
            messageBodyPart.setHeader("Content-ID","memememe");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            Transport.send(message);
        }  catch (MessagingException e) {
            e.printStackTrace();
        }
        session =null;
    }


    public static void receiveMail() throws MessagingException, IOException {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");       // 协议
        props.setProperty("mail.pop3.port", "110");             // 端口
        props.setProperty("mail.pop3.host", "pop.163.com");    // pop3服务器

        Session session = Session.getInstance(props);
        Store store = session.getStore("pop3");
        store.connect(home_address, password);

        Folder folder = store.getFolder("INBOX");        //获取收件箱
        folder.open(Folder.READ_WRITE);

        Message[] message = folder.getMessages();

        //////
        System.out.println(message.length);
        if(message.length == 0) {
            System.out.println("No message");
            return;
        }
        for(int i = 0;i<message.length;++i) {
            String content = message[i].getContent().toString();
            System.out.println(content);
        }


        /*
        Properties props = new Properties();

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("pop3");
        store.connect(receivehost, home_address, password);
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message message[] = folder.getMessages();

        BufferedReader reader = new BufferedReader (
                new InputStreamReader(System.in));

        System.out.println(message.length);
        if(message.length == 0) {
            System.out.println("No message");
            return;
        }
        for(int i = 0;i<message.length;++i) {
            String content = message[i].getContent().toString();
            System.out.println(content);
        }

        for (int i=0, n=message.length; i<n; i++) {
            System.out.println("第"+(i+1)+"封邮件: " + message[i].getFrom()[0]
                    + "/t" + message[i].getSubject());

            System.out.println("Do you want to read message? " +
                    "[YES to read/QUIT to end]");
            String line = reader.readLine();
            if ("YES".equals(line)) {
                String s = message[i].getContent().toString();
                s = s.replaceAll("[\r\n]","");
                System.out.print(s);
                System.out.println();
            } else if ("QUIT".equals(line)) {
                break;
            }
        }
        */


        // Close connection
        folder.close(false);
        store.close();
    }

    //get the email address from the database
    public static emailAddress[] getemailAddress() throws SQLException, IllegalAccessException, InstantiationException {
        emailAddress[] addresses = new emailAddress[N];
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String url = "jdbc:mysql://localhost:3306/hw4" +
                    "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String user = "root";
            String password = "1a2b3c4d";
            conn = DriverManager.getConnection(url,user,password);
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from address");
            int i=0;
                while (rs.next()) {
                    addresses[i] =new emailAddress();
                    addresses[i].Name = rs.getString(1);
                    addresses[i].Address = rs.getString(2);
                    i++;
                }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        conn.close();
        stmt.close();
        rs.close();

        return  addresses;
    }

    private static Connection getConn() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/samp_db";
        String username = "root";
        String password = "1a2b3c4d";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    public static void main(String[] args) throws SQLException, InstantiationException, IllegalAccessException, MessagingException, IOException {
        emailAddress[] addresses ;
        addresses =getemailAddress();//get the email address from the database
        //sendMail(addresses[0].getAddress(),addresses[0].getName());
        //sendMail(addresses[1].getAddress(),addresses[1].getName());
        //sendMail(addresses[2].getAddress(),addresses[2].getName());



        //sendMailWithFile(addresses[1].getAddress(),addresses[1].getName(),"file/1.txt");

        //sendMailWithImage(addresses[1].getAddress(),addresses[1].getName(),"file/2.jpg");


        //receiveMail();
    }
}
